package com.minminaya.source;

public class Algorithm_6 {


    public static int min(int[] numbers) {

        if (numbers == null || numbers.length == 0) {
            throw new RuntimeException("invalid input");
        }

        int firstNum = 0;
        int endNum = numbers.length - 1;
        //初始值
        int middleNum = firstNum;
        while (numbers[firstNum] >= numbers[middleNum]) {
            if (endNum - firstNum == 1) {
                return numbers[endNum];
            }

            middleNum = firstNum + (endNum - middleNum) / 2;

            if (numbers[middleNum] == numbers[firstNum] && numbers[middleNum] == numbers[endNum]) {
                return minInOrder(numbers, firstNum, endNum);
            }

            if (numbers[middleNum] >= numbers[firstNum]) {
                //因为是连续的数组，如果中间值大于第一个值，说明小的值在中间值的后面，那么二分期待应该变为中间点
                firstNum = middleNum;
            } else if (numbers[middleNum] <= numbers[endNum]) {
                endNum = middleNum;
            }
        }
        return numbers[middleNum];
    }

    /**
     * 取数组中的最小值
     */
    private static int minInOrder(int[] numbers, int firstNum, int endNum) {
        int result = numbers[firstNum];
        for (int i = firstNum + 1; i < endNum; i++) {
            if (result > numbers[i]) {
                result = numbers[i];
            }
        }
        return result;
    }

}
